<template>
    <div class="container">
        <Breadcrumb :items="['menu.store', 'menu.store.pickup']" />
        <a-card :title="$t('menu.store.pickup')">


            <a-space>
                <a-button type="primary" shape="round" @click="showDayGoodsList">
                    查看/打印备货清单
                </a-button>

                <a-button type="primary" shape="round" @click="showPickupOrdersSummary">
                    各配送点订单明细
                </a-button>
            </a-space>
        </a-card>

        <a-drawer :visible="dayGoodsListVisible" width="850px" title="查看/打印备货清单" @cancel="dayGoodsListVisible = false">
            <template #footer>
                <a-space>
                <a-button v-print="printObj" v-if="searchForm.startDate && searchForm.endDate && dayGoodsListData.length > 0" type="primary" shape="round" @click="printDayGoodsList">
                    打印
                </a-button>
                </a-space>
            </template>
            <div>
                <!-- 日期搜索区域 -->
                <div class="search-section">
                    <a-space size="large">
                        <div class="search-item">
                            <label class="search-label">开始日期：</label>
                            <a-date-picker v-model="searchForm.startDate" placeholder="请选择开始日期" style="width: 200px" />
                        </div>
                        <div class="search-item">
                            <label class="search-label">结束日期：</label>
                            <a-date-picker v-model="searchForm.endDate" placeholder="请选择结束日期" style="width: 200px" />
                        </div>
                        <div class="search-item">
                            <a-button type="primary" @click="handleDateSearch" :loading="loading">
                                搜索
                            </a-button>
                            <a-button @click="handleResetSearch">
                                重置
                            </a-button>
                        </div>
                    </a-space>
                </div>
                <div id="printMe" >
                    <a-typography-title :heading="2">备货清单</a-typography-title>
                    <a-space style="margin-bottom:20px;">
                        <template v-if="searchForm.startDate && searchForm.endDate">
                            <div>开始日期：{{ searchForm.startDate }}</div>
                            <div>结束日期：{{ searchForm.endDate }}</div>
                        </template>
                        <template v-else>
                            <div style="color:red;font-weight:bold;">请选择开始日期和结束日期</div>
                        </template>
                    </a-space>
                    <a-table :pagination="false" :data="dayGoodsListData">
                        <template #columns>
                            <a-table-column title="商品ID" data-index="goods_id" />
                            <a-table-column title="商品名称" data-index="name" />
                            <a-table-column title="规格信息" data-index="specs">
                                <template #cell="{ record }">
                                    <div v-if="record.specs">
                                        <div v-for="(spec, specId) in record.specs" :key="specId" class="spec-item">
                                            <span class="spec-name">{{ spec.name }}</span>
                                            <span class="spec-quantity">数量: {{ spec.quantity }}</span>
                                        </div>
                                    </div>
                                </template>
                            </a-table-column>
                        </template>
                    </a-table>
                </div>
            </div>
        </a-drawer>

        <!-- 配送点订单明细抽屉 -->
        <a-drawer :visible="pickupOrdersVisible" width="1200px" title="各配送点订单明细" @cancel="pickupOrdersVisible = false">
            <template #footer>
                <a-space>
                    <a-button v-print="pickupOrdersPrintObj" v-if="pickupOrdersData.length > 0" type="primary" shape="round">
                        打印订单明细
                    </a-button>
                </a-space>
            </template>
            <div>
                <!-- 日期搜索区域 -->
                <div class="search-section">
                    <a-space size="large">
                        <div class="search-item">
                            <label class="search-label">查询日期：</label>
                            <a-date-picker v-model="pickupOrdersSearchForm.date" placeholder="请选择查询日期" style="width: 200px" />
                        </div>
                        <div class="search-item">
                            <a-button type="primary" @click="handlePickupOrdersSearch" :loading="pickupOrdersLoading">
                                搜索
                            </a-button>
                            <a-button @click="handlePickupOrdersReset">
                                重置
                            </a-button>
                        </div>
                    </a-space>
                </div>

                <!-- 统计信息 -->
                <div v-if="pickupOrdersData.length > 0" class="summary-info">
                    <a-row :gutter="16">
                        <a-col :span="8">
                            <a-statistic title="配送点数量" :value="pickupOrdersSummary.total_pickup_points" />
                        </a-col>
                        <a-col :span="8">
                            <a-statistic title="订单总数" :value="pickupOrdersSummary.total_orders" />
                        </a-col>
                        <a-col :span="8">
                            <a-statistic title="查询日期" :value="pickupOrdersSummary.query_date" />
                        </a-col>
                    </a-row>
                </div>

                <!-- 配送点订单列表 -->
                <div id="pickupOrdersPrintContent">
                    <div v-for="(group, groupIndex) in pickupOrdersData" :key="groupIndex" class="pickup-group break-after">
                        <div class="pickup-point-header">
                            <h3>{{ group.pickup_point?.name}}【用户提货单】</h3>
                            <div class="pickup-point-info">
                                <div>
                                    提货日期：{{ pickupOrdersSearchForm.date }}
                                </div>
                                <div>门店地址：{{ group.pickup_point?.address || '未知地址' }}</div>
                            </div>
                        </div>

                        <div class="pickup-tip">
                            订单按手机号最后一位排序。
                        </div>

                        <!-- 每个订单一个表格 -->
                        <div v-for="(order, orderIndex) in group.orders" :key="orderIndex" class="order-table-container">
                            <div class="order-header">
                                <div class="order-info">
                                    <span class="user-name">{{ order.user_name }}</span>
                                    <span class="user-phone">{{ order.user_phone }}</span>
                                </div>
                            </div>
                            
                            <a-table 
                                :pagination="false" 
                                size="large" 
                                :bordered="{ cell: true }" 
                                :data="order.items || []" 
                                class="order-items-table">
                                <template #columns>
                                    <a-table-column title="商品明细" data-index="goods_title">
                                        <template #cell="{ record }">
                                            <div class="item-title">
                                                {{ record.goods_title }} {{ record.sku_spec_names ? ' / ' + record.sku_spec_names : '' }}
                                            </div>
                                        </template>
                                    </a-table-column>
                                    <a-table-column title="数量" data-index="quantity" width="100">
                                        <template #cell="{ record }">
                                            <div class="item-quantity">{{ record.quantity }}</div>
                                        </template>
                                    </a-table-column>
                                    <a-table-column title="提货确认" width="100" />
                                </template>
                            </a-table>
                        </div>
                    </div>
                </div>
            </div>
        </a-drawer>
    </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue';
import { Message } from '@arco-design/web-vue';
import dayjs from 'dayjs';
import { getPickUpPointDayGoodsList, getPickupOrdersSummary, type PickupOrdersGroup, type PickupOrdersSummaryRes } from '@/api/pickUpPoint';

const loading = ref(false);

// 配送点订单明细相关
const pickupOrdersVisible = ref(false);
const pickupOrdersLoading = ref(false);
const pickupOrdersData = ref<PickupOrdersGroup[]>([]);
const pickupOrdersSummary = ref<PickupOrdersSummaryRes>({
    list: [],
    total_pickup_points: 0,
    total_orders: 0,
    query_date: ''
});
const pickupOrdersSearchForm = ref({
    date: null
});

//  查看/打印备货清单
const dayGoodsListVisible = ref(false);
const dayGoodsListData = ref([]);
// 搜索表单数据
const searchForm = ref({
    startDate: null,
    endDate: null
});

const fetchDayGoodsList = () => {
    const params = {};
    if (searchForm.value.startDate) {
        params.startDate = dayjs(searchForm.value.startDate).format('YYYY-MM-DD');
    }
    if (searchForm.value.endDate) {
        params.endDate = dayjs(searchForm.value.endDate).format('YYYY-MM-DD');
    }

    getPickUpPointDayGoodsList(params).then((res) => {
        if (res.data && res.data.list) {
            // 将对象转换为数组格式
            const list = Object.keys(res.data.list).map(key => ({
                goods_id: key,
                ...res.data.list[key]
            }));
            dayGoodsListData.value = list;
        } else {
            dayGoodsListData.value = [];
        }
    }).catch((error) => {
        console.error('获取备货清单失败:', error);
        Message.error('获取备货清单失败');
        dayGoodsListData.value = [];
    });
}

const showDayGoodsList = () => {
    dayGoodsListVisible.value = true;
    // fetchDayGoodsList();
}



// 日期搜索处理
const handleDateSearch = async () => {
    // 验证日期选择
    if (!searchForm.value.startDate || !searchForm.value.endDate) {
        Message.warning('请选择开始日期和结束日期');
        return;
    }

    // 验证日期范围
    if (dayjs(searchForm.value.startDate).isAfter(dayjs(searchForm.value.endDate))) {
        Message.warning('开始日期不能晚于结束日期');
        return;
    }

    loading.value = true;

    try {
        // 调用API获取数据
        await fetchDayGoodsList();
        Message.success('搜索完成');
    } catch (error) {
        console.error('搜索失败:', error);
        Message.error('搜索失败，请重试');
    } finally {
        loading.value = false;
    }
};

// 重置搜索
const handleResetSearch = () => {
    searchForm.value.startDate = null;
    searchForm.value.endDate = null;
    dayGoodsListData.value = [];
    Message.info('已重置搜索条件');
};

// 配送点订单明细功能
const showPickupOrdersSummary = () => {
    pickupOrdersVisible.value = true;
    // 默认设置为今天
    pickupOrdersSearchForm.value.date = dayjs().format('YYYY-MM-DD');
}

const handlePickupOrdersSearch = async () => {
    if (!pickupOrdersSearchForm.value.date) {
        Message.warning('请选择查询日期');
        return;
    }

    pickupOrdersLoading.value = true;
    try {
        const res = await getPickupOrdersSummary({
            date: dayjs(pickupOrdersSearchForm.value.date).format('YYYY-MM-DD')
        });
        
        if (res.data) {
            pickupOrdersData.value = res.data.list;
            pickupOrdersSummary.value = res.data;
        } else {
            pickupOrdersData.value = [];
        }
    } catch (error) {
        pickupOrdersData.value = [];
    } finally {
        pickupOrdersLoading.value = false;
    }
}

const handlePickupOrdersReset = () => {
    pickupOrdersSearchForm.value.date = null;
    pickupOrdersData.value = [];
    pickupOrdersSummary.value = {
        list: [],
        total_pickup_points: 0,
        total_orders: 0,
        query_date: ''
    };
    Message.info('已重置搜索条件');
}

// 打印备货清单（暂时未实现）
const printDayGoodsList = () => {
    Message.info('打印功能开发中...');
}


const printObj = {
    id: 'printMe',
    popTitle: '打印分组结果',
    popWidth: 800,
    beforeOpenCallback() {
        console.log('打开之前')
    },
    openCallback() {

    },
    closeCallback() {

    }
}

const pickupOrdersPrintObj = {
    id: 'pickupOrdersPrintContent',
    popTitle: '打印配送点订单明细',
    popWidth: 1000,
    beforeOpenCallback() {
        console.log('准备打印配送点订单明细')
    },
    openCallback() {
        console.log('开始打印配送点订单明细')
    },
    closeCallback() {
        console.log('打印配送点订单明细完成')
    }
}



onMounted(() => {

});
</script>

<style scoped>
@media print {
    .new-page {
        page-break-before: always; /* 在此元素前分页 */
    }
    
    .break-after {
        page-break-after: always; /* 在此元素后分页 */
    }
}

.container {
    padding: 0 20px 20px 20px;
}

.search-section {
    margin-bottom: 20px;
    padding: 16px;
    background-color: #f7f8fa;
    border-radius: 6px;
    border: 1px solid #e5e6eb;
}

.search-item {
    display: flex;
    align-items: center;
    gap: 8px;
}

.search-label {
    font-weight: 500;
    color: #1d2129;
    white-space: nowrap;
    min-width: 80px;
}

.search-results {
    margin: 20px 0;
}

.result-info {
    color: #4e5969;
    font-size: 14px;
    margin-bottom: 16px;
}

.spec-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 4px 8px;
    margin: 5px 0;
    background-color: #f7f8fa;
    border-radius: 4px;
    border: 1px solid #e5e6eb;
}

.spec-name {
    font-weight: 500;
    color: #1d2129;
}

.spec-quantity {
    color: #4e5969;
    font-size: 12px;
}

/* 配送点订单明细样式 */
.summary-info {
    margin: 20px 0;
    padding: 16px;
    background-color: #f7f8fa;
    border-radius: 6px;
    border: 1px solid #e5e6eb;
}

.pickup-group {
    overflow: hidden;
    margin-bottom: 30px;
}

.pickup-tip {
    padding: 0 20px;
    font-size:16px;
    font-weight: 600;
    color:#000;
}

.pickup-point-header {
    padding: 16px 20px;
}

.pickup-point-header h3 {
    margin: 0 0 12px 0;
    color: #1d2129;
    font-size: 32px;
    font-weight: 600;
    text-align: center;
}

.pickup-point-info {
    display: flex;
    flex-wrap: wrap;
    flex-direction: column;
    font-size:16px;
}

/* 订单表格容器样式 */
.order-table-container {
    margin: 20px 0;
    border: 1px solid #e5e6eb;
    border-radius: 8px;
    overflow: hidden;
}

.order-header {
    background-color: #f7f8fa;
    padding: 12px 16px;
    border-bottom: 1px solid #e5e6eb;
}

.order-info {
    display: flex;
    align-items: center;
    gap: 20px;
}

.user-name {
    font-size: 16px;
    font-weight: 600;
    color: #1d2129;
}

.user-phone {
    font-size: 14px;
    color: #4e5969;
}

.order-items-table {
    font-size: 16px;
    margin: 0;
}

.order-items-table .arco-table-container {
    border: none;
}


.order-item {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    padding: 8px 0;
    border-bottom: 1px solid #DDDDDD;
}

.order-item:last-child {
    border-bottom: none;
}


.item-title {
    display: block;
    font-weight: 500;
    color: #1d2129;
    line-height: 1.4;
}

.item-spec {
    display: block;
    font-size: 12px;
    color: #86909c;
}

.item-quantity {
    color: #4e5969;
    font-size: 14px;
    font-weight: 500;
    text-align: center;
}

.item-price {
    color: #f53f3f;
    font-weight: 500;
    font-size: 14px;
    text-align: right;
}

.item-total {
    color: #f53f3f;
    font-weight: 600;
    font-size: 14px;
    text-align: right;
}


/* 打印样式 */
@media print {
    .pickup-group {
        page-break-inside: avoid;
        margin-bottom: 20px;
    }
    
    .pickup-point-header {
        background-color: #f5f5f5 !important;
    }
    
    .orders-table {
        font-size: 12px;
    }
    
    .order-item {
        padding: 4px 0;
    }
}
</style>
